﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Serial Console!");
            if (!args.Any())
            {
                foreach (var portName in SerialPort.GetPortNames())
                {
                    Console.WriteLine(portName);
                }
                return;
            }
            SerialPort port;
            try
            {
                port = new SerialPort(args[0]);
                port.BaudRate = int.Parse(args[1]);
                port.DataReceived += port_DataReceived;
                port.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("Port opened");
            Console.WriteLine();
            
            for (; ; )
            {
                string line = Console.ReadLine();
                if (line.ToUpperInvariant() == "QUIT")
                {
                    break;
                }
                else
                {
                    port.Write(line + "\n");
                }
            }
            port.Close();
        }

        static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Console.Write((sender as SerialPort).ReadExisting());
        }
    }
}
